package cn.stylefeng.guns.modular.hx.order.controller;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.http.HttpRequest;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.modular.basic.entity.BasicAddress;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.entity.BasicPutgoods;
import cn.stylefeng.guns.modular.basic.entity.BasicWarehouse;
import cn.stylefeng.guns.modular.basic.model.params.BasicAddressParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicPutgoodsParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicXlbOauth2tokenParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicAddressResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicCustomerResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicPutgoodsResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicXlbOauth2tokenResult;
import cn.stylefeng.guns.modular.basic.service.BasicAddressService;
import cn.stylefeng.guns.modular.basic.service.BasicCustomerService;
import cn.stylefeng.guns.modular.basic.service.BasicPutgoodsService;
import cn.stylefeng.guns.modular.basic.service.BasicWarehouseService;
import cn.stylefeng.guns.modular.basic.service.BasicXlbOauth2tokenService;
import cn.stylefeng.guns.modular.hx.basic.model.params.HxBasicGoodsParam;
import cn.stylefeng.guns.modular.hx.basic.model.params.HxBasicUnitCodeParam;
import cn.stylefeng.guns.modular.hx.basic.model.result.HxBasicGoodsResult;
import cn.stylefeng.guns.modular.hx.basic.model.result.HxBasicUnitCodeResult;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicGoodsService;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicUnitCodeService;
import cn.stylefeng.guns.modular.hx.order.entity.HxOrderOut;
import cn.stylefeng.guns.modular.hx.order.entity.HxOrderOutDetailed;
import cn.stylefeng.guns.modular.hx.order.model.params.HxOrderOutDetailedParam;
import cn.stylefeng.guns.modular.hx.order.model.params.HxOrderOutParam;
import cn.stylefeng.guns.modular.hx.order.model.result.HxOrderOutResult;
import cn.stylefeng.guns.modular.hx.order.service.HxOrderOutDetailedService;
import cn.stylefeng.guns.modular.hx.order.service.HxOrderOutService;
import cn.stylefeng.guns.modular.hx.order.utils.EmojiTransferUtil;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageStockParam;
import cn.stylefeng.guns.modular.kh.entity.KhWare;
import cn.stylefeng.guns.modular.kh.service.KhWareService;
import cn.stylefeng.guns.modular.order.model.params.DealWithParam;
import cn.stylefeng.guns.sys.modular.system.model.result.DictResult;
import cn.stylefeng.guns.sys.modular.system.service.DictService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.guns.sys.modular.system.entity.Dept;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.DeptService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;


/**
 * 出库订单表控制器
 *
 * @author zhucx
 * @Date 2023-08-30 15:16:23
 */
@Controller
@RequestMapping("/hxOrderOut")
public class HxOrderOutController extends BaseController {

    private String PREFIX = "/hx/order/hxOrderOut";

    @Autowired
    private HxOrderOutService hxOrderOutService;

    @Autowired
    private UserService userService;

    @Autowired
    private DictService dictService;

    @Autowired
    private BasicCustomerService basicCustomerService;

    @Autowired
    private BasicWarehouseService basicWarehouseService;

    @Autowired
    private HxOrderOutDetailedService hxOrderOutDetailedService;

    @Autowired
    private BasicPutgoodsService basicPutgoodsService;

    @Autowired
    private KhWareService khWareService;

    private Lock lock = new ReentrantLock();

    /**
     * 跳转到主页面
     *
     * @author zhucx
     * @Date 2023-08-30
     */
    @RequestMapping("")
    public String index(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择仓库
        model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId, deliverId, user.getOperateId()));
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return PREFIX + "/hxOrderOut.html";
    }

    /**
     * 跳转到查询页面
     *
     * @author zhucx
     * @Date 2023-08-05
     */
    @RequestMapping("toQuery")
    public String toQuery(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择仓库
        model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId, deliverId, user.getOperateId()));
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId, deliverId, user.getOperateId()));
        return PREFIX + "/query.html";
    }

    /**
     * 跳转到批量提交页面
     *
     * @author zhucx
     * @Date 2023-08-30
     */
    @RequestMapping("tobtnSubmission")
    public String tobtnSubmission() {
        return PREFIX + "/btnSubmission.html";
    }

    /**
     * 跳转到批量提交页面
     *
     * @author zhucx
     * @Date 2023-08-30
     */
    @RequestMapping("tobtnSubmission2")
    public String tobtnSubmission2() {
        return PREFIX + "/btnSubmission2.html";
    }

    /**
     * 跳转到批量提交页面
     *
     * @author zhucx
     * @Date 2023-08-30
     */
    @RequestMapping("tobtnSubmission3")
    public String tobtnSubmission3(Model model) {
        List<DictResult> waveNumList = this.dictService.findByDicttypeCode2("KH_BC");
        model.addAttribute("waveNumList", waveNumList);
        return PREFIX + "/btnSubmission3.html";
    }

    /**
     * 批量提交
     */
    @RequestMapping("/btnSubmission")
    @ResponseBody
    public ResponseData btnSubmission(HxOrderOutParam hxOrderOutParam) {
        ResponseData data = new ResponseData();
        data.setSuccess(true);
        User user = userService.getcurrentUser();
        lock.lock();//获取锁
        try {
            for (String order : hxOrderOutParam.getOrders()) {
                HxOrderOutParam param = new HxOrderOutParam();
                param.setOrderOutNumber(order);
                HxOrderOutResult hxOrderOutResult = hxOrderOutService.findBySpec(param);
                if (!"待提交".equals(hxOrderOutResult.getOrderState()) && !"撤回".equals(hxOrderOutResult.getOrderState())) {
                    data.setSuccess(false);
                    data.setMessage(order + "单据状态已变化，请刷新重试");
                    return data;
                }
                QueryWrapper<HxOrderOutDetailed> queryWrapper = new QueryWrapper<HxOrderOutDetailed>();
                queryWrapper.eq("order_out_number", order);
                int count = hxOrderOutDetailedService.count(queryWrapper);
                if (count <= 0) {
                    data.setSuccess(false);
                    data.setMessage("请先添加商品明细");
                    return data;
                }
            }
//	        hxOrderOutService.outSingle(hxOrderOutParam,user,data);//生成拣货单

            hxOrderOutService.outSingleJbsl(hxOrderOutParam, user, data);//生成拣货单
            if (!data.getSuccess()) {
                return data;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//释放锁
        }
        return data;
    }

    /**
     * 批量提交
     */
    @RequestMapping("/btnSubmissionNew")
    @ResponseBody
    public ResponseData btnSubmissionNew(HxOrderOutParam hxOrderOutParam) {
        ResponseData data = new ResponseData();
        data.setSuccess(true);
        User user = userService.getcurrentUser();
        lock.lock();//获取锁
        try {
            return hxOrderOutService.outSingleNew(hxOrderOutParam, user);//生成拣货单
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//释放锁
        }
        return data;
    }

    /**
     * 批量提交
     */
    @RequestMapping("/btnSubmission3")
    @ResponseBody
    public ResponseData btnSubmission3(HxOrderOutParam hxOrderOutParam) {
        ResponseData data = new ResponseData();
        data.setSuccess(true);
        User user = userService.getcurrentUser();
        try {
            // data = hxOrderOutService.btnSubmission3(hxOrderOutParam,user);//生成拣货单

            if (ToolUtil.isEmpty(user.getOperateId())) {
                return ResponseData.error("用户无权限");
            }
            // 根据波次号，查询对应门店
            if (ToolUtil.isEmpty(hxOrderOutParam.getWaveNum())) {
                return ResponseData.error("请输入波次号");
            }
            List<KhWare> khWareList = khWareService.lambdaQuery()
                    .eq(KhWare::getWaveNum, hxOrderOutParam.getWaveNum())
                    .eq(KhWare::getOperateId, user.getOperateId())
                    .orderByAsc(KhWare::getGetUnitSort)
                    .list();

            List<BasicCustomerResult> basicCustomerResultList = basicCustomerService.findAvailableList(user.getDeptId(), user.getDeliverId(), user.getOperateId());
            BasicCustomerResult basicCustomerResult = basicCustomerResultList.get(0);

            Set<String> mdBmSet = new HashSet<>();
            for (KhWare obj : khWareList) {
                mdBmSet.add(obj.getGetUnitNumber());
            }

            List<BasicPutgoods> basicPutgoodsList = this.basicPutgoodsService.lambdaQuery()
                    .in(BasicPutgoods::getUnitNumber, mdBmSet)
                    .eq(BasicPutgoods::getPutgoodsCustomerId, basicCustomerResult.getId())
                    .list();

            Set<Integer> mdIdSet = new HashSet<>();
            for (BasicPutgoods obj : basicPutgoodsList) {
                mdIdSet.add(obj.getId());
            }
            // 根据门店 查询当前待提交数据
            List<HxOrderOut> hxOrderOutList = this.hxOrderOutService.lambdaQuery()
                    .eq(HxOrderOut::getGetUnitId, mdIdSet)
                    .eq(HxOrderOut::getCustomerId, basicCustomerResult.getId())
                    .in(HxOrderOut::getOrderType, "待提交", "撤回")
//					.last(" limit 4 ")
                    .list();

            // 按照门店 组装
            Map<String, List<Integer>> hxOrderOutIds = new HashMap<>();
            for (HxOrderOut obj : hxOrderOutList) {
                if (ToolUtil.isEmpty(hxOrderOutIds.get(obj.getGetUnitId().toString()))) {
                    List<Integer> addList = new ArrayList<>();
                    addList.add(obj.getId());
                    hxOrderOutIds.put(obj.getGetUnitId().toString(), addList);
                } else {
                    hxOrderOutIds.get(obj.getGetUnitId().toString()).add(obj.getId());
                }
            }

            for (String key : hxOrderOutIds.keySet()) {
                String[] orders = new String[]{};
                hxOrderOutIds.get(key).toArray(orders);
                hxOrderOutParam.setOrders(orders);
                ResponseData responseData = hxOrderOutService.outSingleJbsl(hxOrderOutParam, user, data);//生成拣货单
                if (!responseData.getSuccess()) {
                    return responseData;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    /**
     * 拉取新零帮出库申请单页面
     */
    @RequestMapping("/topullxlbOutapplicationorder")
    public String topullxlbOutapplicationorder(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId, deliverId, user.getOperateId()));

        //查询可选择仓库
        model.addAttribute("wlist", basicWarehouseService.findAvailableList(deptId, deliverId, user.getOperateId()));

        BasicPutgoodsParam basicPutgoodsParam = new BasicPutgoodsParam();
        basicPutgoodsParam.setUnitCategory("发货");
        basicPutgoodsParam.setUnitType("配送中心");
        basicPutgoodsParam.setDeptId(deptId);
        List<BasicPutgoodsResult> pglist = basicPutgoodsService.findListBySpec(basicPutgoodsParam, user.getOperateId());
        model.addAttribute("pglist", pglist);
        return PREFIX + "/pullxlbOutapplicationorder.html";
    }

    /**
     * 拉取天财商龙出库申请单页面
     */
    @RequestMapping("/topulltcslOutapplicationorder")
    public String topulltcslOutapplicationorder(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId, deliverId, user.getOperateId()));

        //查询可选择仓库
        model.addAttribute("wlist", basicWarehouseService.findAvailableList(deptId, deliverId, user.getOperateId()));

        BasicPutgoodsParam basicPutgoodsParam = new BasicPutgoodsParam();
        basicPutgoodsParam.setUnitCategory("发货");
        basicPutgoodsParam.setUnitType("配送中心");
        basicPutgoodsParam.setDeptId(deptId);
        List<BasicPutgoodsResult> pglist = basicPutgoodsService.findListBySpec(basicPutgoodsParam, user.getOperateId());
        model.addAttribute("pglist", pglist);
        return PREFIX + "/pulltcslOutapplicationorder.html";
    }

    public static void main(String[] args) {
        String str = "6866800013185";
        System.out.println(str.indexOf("68668"));
    }

    /**
     * 拉取出库申请单
     *
     * @author zhucx
     * @Date 2024-04-17
     */
    @RequestMapping("/pullxlbOutapplicationorder")
    @ResponseBody
    public ResponseData pullxlbOutapplicationorder(String modified_begin, String modified_end, Long customerId, Long setUnitId, Long setWarehouseId, String cover) {
        ResponseData data = new ResponseData();
        if (setUnitId == null) {
            return ResponseData.error("请选择装货单位");
        }
//        String url = "https://test-api.xlbsoft.com/api/hxl.open.wms.outapplicationorder.findbyupdatetime";
        String url = "https://hxl-api.xlbsoft.com/api/hxl.open.wms.outapplicationorder.findbyupdatetime";
        List<String> update_times = new ArrayList<String>();
        update_times.add(modified_begin);
        update_times.add(modified_end);
        BasicCustomer r = basicCustomerService.getById(customerId);
        BasicWarehouse w = basicWarehouseService.getById(setWarehouseId);

        if (ToolUtil.isEmpty(r.getStoreIdXlb())) {
            return ResponseData.error("请维护新零帮发货门店id");
        }
        if (ToolUtil.isEmpty(r.getGsnumber())) {
            return ResponseData.error("请维护新零帮公司号");
        }
        if (ToolUtil.isEmpty(w.getWarehouseXlbId())) {
            return ResponseData.error("请维护新零帮仓库id");
        }

        BasicPutgoods fh = basicPutgoodsService.getById(setUnitId);
        BasicAddressParam basicAddressParam = new BasicAddressParam();
        basicAddressParam.setPutgoodsId(Long.parseLong(fh.getId().toString()));
        BasicAddressResult addressResult = basicAddressService.findBySpec(basicAddressParam);
        if (addressResult == null) {
            return ResponseData.error("装货地址不存在！请维护");
        }

        if (ToolUtil.isNotEmpty(cover) && cover.equals("1")) {//清空待提交单据
            HxOrderOutParam orderOutParam1 = new HxOrderOutParam();
            orderOutParam1.setCustomerId(customerId);
            orderOutParam1.setSetWarehouseId(setWarehouseId);
            orderOutParam1.setSetUnitId(setUnitId);
            orderOutParam1.setOrderState("待提交");
            List<HxOrderOutResult> olist = hxOrderOutService.findOrderOutNumberListBySpec(orderOutParam1);
            if (olist.size() > 0) {
                List<Integer> deleteolist = new ArrayList<Integer>();
                List<String> deletedlist = new ArrayList<String>();
                for (HxOrderOutResult op : olist) {
                    deleteolist.add(op.getId());
                    deletedlist.add(op.getOrderOutNumber());
                }
                hxOrderOutService.deletebyids(deleteolist);
                hxOrderOutDetailedService.deletebyorders(deletedlist);
            }
        }

        BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
        oauth2tokenParam.setDeliverId(r.getDeliverId());
        oauth2tokenParam.setGsnumber(r.getGsnumber());
        BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
        if (oauth2tokenResult != null) {
            if (ToolUtil.isNotEmpty(oauth2tokenResult.getOauth2TokenXlb())) {
                JSONObject json = new JSONObject();
                json.put("store_id", r.getStoreIdXlb());
                json.put("storehouse_id", w.getWarehouseXlbId());
                json.put("update_times", update_times);
                String post = HttpRequest.post(url)
                        .header("Authorization", "bearer " + oauth2tokenResult.getOauth2TokenXlb())
                        .body(json.toString()).execute().body();
//				System.out.println("================json："+json+"========================");
//				System.out.println("================post："+post+"========================");
                JSONObject jsonObject = new JSONObject(post);
                if (jsonObject.get("code").toString().equals("0")) {
                    User user = userService.getcurrentUser();
                    List<HxOrderOutParam> olist = new ArrayList<HxOrderOutParam>();//批量保存的 出库订单list
                    List<HxOrderOutDetailedParam> detailedList = new ArrayList<HxOrderOutDetailedParam>();//批量保存的 订单商品明细list
                    Long deptId = user.getDeptId();
                    Long deliverId = user.getDeliverId();
                    DealWithParam dealWithParam = new DealWithParam();
                    dealWithParam.setNewCustomersflag(false);
                    JSONArray jsonArray = new JSONArray();
                    try {
                        jsonArray = new JSONArray(jsonObject.get("data").toString());
                    } catch (Exception e) {
                        return ResponseData.error("未拉取到数据");
                    }
                    BigDecimal as = new BigDecimal("0");
                    Map<String, HxBasicGoodsResult> goodsMap = new HashMap<>();
                    Map<String, String> oMap = new HashMap<>();
                    if (jsonArray.length() > 0) {
                        HxBasicGoodsParam hxgoodsp = new HxBasicGoodsParam();
                        hxgoodsp.setGoodsCustomerId(r.getId());
                        List<HxBasicGoodsResult> hxg = hxBasicGoodsService.findListBySpec(hxgoodsp);
                        for (HxBasicGoodsResult gr : hxg) {
                            goodsMap.put(gr.getGoodsXlbId(), gr);
                        }
                        HxOrderOutParam hxop = new HxOrderOutParam();
                        hxop.setCustomerId(customerId);
                        List<HxOrderOutResult> hxoo = hxOrderOutService.findOrderListBySpec(hxop);
                        for (HxOrderOutResult or : hxoo) {
                            oMap.put(or.getOrderOutNumber(), or.getOrderOutNumber());
                        }
                    }
                    for (Object object : jsonArray) {
                        JSONObject jsonObject2 = new JSONObject(object.toString());

                        HxOrderOutParam opp = new HxOrderOutParam();
                        //新增出库订单
                        opp.setCustomerId(customerId);//客户id
                        opp.setCustomerName(r.getCustomerName());//客户名称
                        opp.setOrderState("待提交");//订单状态
                        opp.setXlbSetUnitId(r.getStoreIdXlb());
                        opp.setSetUnit(fh.getPutgoodsName());//装货单位
                        opp.setSetUnitId(Long.parseLong(fh.getId().toString()));//装货单位id
                        opp.setSetLocation(addressResult.getAddress());//装货地址
                        opp.setSetLocationId(Long.parseLong(addressResult.getId().toString()));//装货地址id
                        opp.setSetPeople(addressResult.getContacts());//联系人
                        opp.setSetTel(addressResult.getTel());//联系电话
                        opp.setXlbSetWarehouseId(w.getWarehouseXlbId());
                        opp.setSetWarehouseId(setWarehouseId);//仓库id
                        opp.setSetWarehouse(w.getWarehouseName());//仓库名称
                        opp.setCreateUserName(user.getName());//制单人名称
                        opp.setCreateTime(new Date());
                        opp.setDeliverId(deliverId);//交付id
                        opp.setDeptId(deptId);//部门id

                        String fid = jsonObject2.get("fid").toString();
                        if (ToolUtil.isNotEmpty(fid) && !fid.equals("null")) {//单据号
                            opp.setOrderOutNumber(fid);//订单号
                            //校验单号是否已添加
                            String orderOutNumber = oMap.get(fid);
                            if (orderOutNumber != null) {
                                continue;
                            }
                            //校验单号是否已存在 集合里
                            for (HxOrderOutParam opp2 : olist) {
                                if (opp2.getOrderOutNumber().equals(fid)) {
                                    continue;
                                }
                            }
                        } else {
                            continue;
                        }

                        String order_type_name = jsonObject2.get("order_type_name").toString();
                        if (ToolUtil.isNotEmpty(order_type_name) && !order_type_name.equals("null")) {//出库单据类型
                            opp.setOrderType(order_type_name);
                        }

                        String erp_order_types = jsonObject2.get("erp_order_types").toString();
                        if (ToolUtil.isNotEmpty(erp_order_types) && !erp_order_types.equals("null")) {//关联单据类型
                            opp.setXlbRequestOrderType(erp_order_types);
                        }

                        String delivery_date = jsonObject2.get("delivery_date").toString();
                        if (ToolUtil.isNotEmpty(delivery_date) && !delivery_date.equals("null")) {//配送日期
                        }
                        opp.setPeisongTime(DateUtil.getDate());

                        String quantity1 = jsonObject2.get("quantity").toString();
                        if (ToolUtil.isNotEmpty(quantity1) && !quantity1.equals("null")) {//申请数量
                            BigDecimal quantitybig1 = new BigDecimal(quantity1);
                            if (quantitybig1.compareTo(as) != 1) {
                                continue;
                            }
                        }

                        String memo = jsonObject2.get("memo").toString();
                        if (ToolUtil.isNotEmpty(memo) && !memo.equals("null")) {//备注
                            if (memo.length() < 100) {
                                opp.setNotes(EmojiTransferUtil.emojiEncode(memo));
                            }
                        }

                        String client_id = jsonObject2.get("client_id").toString();
                        if (ToolUtil.isNotEmpty(client_id) && !client_id.equals("null")) {//收货客户id
                            opp.setXlbClientId(client_id);
                        }

                        String erp_client_id = jsonObject2.get("erp_client_id").toString();
                        if (ToolUtil.isNotEmpty(erp_client_id) && !erp_client_id.equals("null")) {//erp收货客户id
                        }

                        String client_name = jsonObject2.get("client_name").toString();
                        if (ToolUtil.isNotEmpty(client_name) && !client_name.equals("null")) {//客户名称
                            opp.setGetUnit(client_name);
                        }

                        JSONArray jsonArray2 = new JSONArray(jsonObject2.get("details").toString());
                        if (jsonArray2.length() == 0) {
                            continue;
                        }
                        toDealWith3(opp, r, dealWithParam, oauth2tokenResult.getOauth2TokenXlb(), client_id, erp_client_id);//处理单位和地址
                        olist.add(opp);

                        for (Object object2 : jsonArray2) {
                            JSONObject jsonObject3 = new JSONObject(object2.toString());

                            HxOrderOutDetailedParam hxd = new HxOrderOutDetailedParam();

                            String quantity = jsonObject3.get("quantity").toString();
                            if (ToolUtil.isEmpty(quantity) || quantity.equals("null")) {//申请数量
                                continue;
                            }

                            String ratio = jsonObject3.get("ratio").toString();
                            if (ToolUtil.isEmpty(ratio) || ratio.equals("null")) {//换算率
                                continue;
                            }

                            String unit = jsonObject3.get("unit").toString();
                            if (ToolUtil.isEmpty(unit) || unit.equals("null")) {//单位
                                continue;
                            }

                            String item_code = jsonObject3.get("item_code").toString();
                            if (ToolUtil.isEmpty(item_code) || item_code.equals("null")) {//商品代码
                                continue;
                            }

                            String item_id = jsonObject3.get("item_id").toString();
                            if (ToolUtil.isEmpty(item_id) || item_id.equals("null")) {//商品代码
                                continue;
                            } else {
                                if (item_id.indexOf("68668") == 0) {
                                    continue;
                                }
                            }

                            HxBasicGoodsResult hxBasicGoodsResult = goodsMap.get(item_id);
                            if (hxBasicGoodsResult == null) {
                                return ResponseData.error(item_code + "商品不存在" + fid);
                            }

                            BigDecimal quantitybig = new BigDecimal(quantity);
                            BigDecimal ratiobig = new BigDecimal(ratio);
//							BigDecimal psRate = new BigDecimal(hxBasicGoodsResult.getPsRate());
//							if(order_type_name.equals("采购退货")) {
//								if(psRate.compareTo(ratiobig) == -1) {
//									//如果配送换算率 小于 xlb换算率：  配送数量  =  xlb数量*（xlb换算率/配送换算率）
//									BigDecimal div = ratiobig.divide(psRate,3, BigDecimal.ROUND_HALF_DOWN);
//									BigDecimal divv_n = quantitybig.multiply(div).setScale(3, BigDecimal.ROUND_HALF_DOWN);
//									quantitybig = divv_n;
//									ratiobig = psRate;
//								}
//								if(psRate.compareTo(ratiobig) == 1) {
//									//如果配送换算率 大于 xlb换算率：  配送数量  =  xlb数量/（配送换算率/xlb换算率）
//									BigDecimal div = psRate.divide(ratiobig,3, BigDecimal.ROUND_HALF_DOWN);
//									BigDecimal divv_n = quantitybig.divide(div,3, BigDecimal.ROUND_HALF_DOWN);
//									quantitybig = divv_n;
//									ratiobig = psRate;
//								}
//							}
                            BigDecimal basicNum = quantitybig.multiply(ratiobig).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                            if (basicNum.compareTo(as) != 1) {
                                continue;
                            }
                            hxd.setXlbGoodsId(hxBasicGoodsResult.getGoodsXlbId());
                            hxd.setJibenNum(basicNum + "");
                            hxd.setJibenUnit(hxBasicGoodsResult.getJibenUnit());
                            BigDecimal psNum = new BigDecimal("0");
                            BigDecimal goodsVolume = new BigDecimal(hxBasicGoodsResult.getGoodsVolume());
                            BigDecimal goodsWeight = new BigDecimal(hxBasicGoodsResult.getGoodsWeight());
                            BigDecimal goodsPrice = new BigDecimal("0");

                            hxd.setUnit(unit);
                            hxd.setRate(ratio);
                            BigDecimal jbRate = new BigDecimal("1");
                            BigDecimal cgRate = new BigDecimal(hxBasicGoodsResult.getCgRate());
//							if(psRate.compareTo(jbRate) == 1) {
//								psNum = basicNum.divide(psRate,3, BigDecimal.ROUND_HALF_DOWN);
//							} else {
//								psNum = basicNum;
//							}
//							if(psNum.compareTo(quantitybig) != 0) {
//								if(!order_type_name.equals("采购退货")) {
//									return ResponseData.error(fid+"中"+item_code+"商品计算时出错，请检查换算率！");
//								}
//							}
                            if (ratiobig.compareTo(cgRate) == -1) {
                                //如果配送换算率 小于 采购换算率：  配送体积  =  采购体积/（采购换算率/配送换算率）
                                BigDecimal div = cgRate.divide(ratiobig, 3, BigDecimal.ROUND_HALF_DOWN);
                                BigDecimal divv_v = goodsVolume.divide(div, 4, BigDecimal.ROUND_HALF_DOWN);
                                goodsVolume = divv_v;
                                BigDecimal divv_w = goodsWeight.divide(div, 3, BigDecimal.ROUND_HALF_DOWN);
                                goodsWeight = divv_w;
                            }
                            if (ratiobig.compareTo(cgRate) == 1) {
                                //如果配送换算率 大于 采购换算率：  配送体积  =  采购体积*（配送换算率/采购换算率）
                                BigDecimal div = ratiobig.divide(cgRate, 3, BigDecimal.ROUND_HALF_DOWN);
                                BigDecimal divv_v = goodsVolume.multiply(div).setScale(4, BigDecimal.ROUND_HALF_DOWN);
                                goodsVolume = divv_v;
                                BigDecimal divv_w = goodsWeight.multiply(div).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                                goodsWeight = divv_w;
                            }
                            BigDecimal goodsChargingPs = new BigDecimal(hxBasicGoodsResult.getGoodsChargingPs());
                            goodsPrice = ratiobig.multiply(goodsChargingPs).setScale(3, BigDecimal.ROUND_HALF_DOWN);

                            //创建订单明细
                            hxd.setOrderOutNumber(fid);
                            hxd.setGoodsId(Long.parseLong(hxBasicGoodsResult.getId().toString()));
                            hxd.setGoodsName(hxBasicGoodsResult.getGoodsName());
                            hxd.setGoodsNumber(hxBasicGoodsResult.getGoodsNumber());
                            hxd.setGoodsPcode69(hxBasicGoodsResult.getGoodsPcode69());
                            hxd.setGoodsXcode69(hxBasicGoodsResult.getGoodsXcode69());
                            hxd.setGoodsHcode69(hxBasicGoodsResult.getGoodsHcode69());
                            hxd.setGoodsSpecs(hxBasicGoodsResult.getGoodsSpecs());
                            hxd.setDismantlingParts(hxBasicGoodsResult.getDismantlingParts());

                            hxd.setPsNum(quantity);

                            hxd.setGoodsWeight(goodsWeight.toString());
                            hxd.setOutWeight(quantitybig.multiply(goodsWeight).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
                            hxd.setGoodsVolume(goodsVolume.toString());
                            hxd.setOutVolume(quantitybig.multiply(goodsVolume).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
                            hxd.setGoodsPrice(goodsPrice.toString());
                            hxd.setOutMoney(quantitybig.multiply(goodsPrice).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());

                            detailedList.add(hxd);
                            hxd = new HxOrderOutDetailedParam();
                        }
                        if (olist.size() == 40) {
                            hxOrderOutService.saveBatchList(olist);
                            if (detailedList.size() > 0) {
                                hxOrderOutDetailedService.saveBatchList(detailedList);
                            }
                            olist = new ArrayList<HxOrderOutParam>();
                            detailedList = new ArrayList<HxOrderOutDetailedParam>();
                        }
                    }
                    if (olist.size() > 0) {
                        hxOrderOutService.saveBatchList(olist);
                        if (detailedList.size() > 0) {
                            hxOrderOutDetailedService.saveBatchList(detailedList);
                        }
                    }
                    data.setSuccess(true);
                    if (dealWithParam.isNewCustomersflag()) {
                        data.setCode(450);
                        data.setMessage(dealWithParam.getNewCustomers().replaceAll("null", ""));
                    }
                } else {
                    String msg = jsonObject.get("msg").toString();
                    return ResponseData.error(msg);
                }
            }
        }
        return ResponseData.success();
    }


    /**
     * 拉取出库申请单
     *
     * @author zhucx
     * @Date 2024-04-17
     */
    @RequestMapping("/pulltcslOutapplicationorder")
    @ResponseBody
    public ResponseData pulltcslOutapplicationorder(String modified_begin, String modified_end, Long customerId, Long setUnitId, Long setWarehouseId, String cover) {
        ResponseData data = new ResponseData();
        if (setUnitId == null) {
            return ResponseData.error("请选择装货单位");
        }
        String url = "https://tcsl.engine.fxscm.net/business/standard/api/v1/bill/out_store";
        List<String> update_times = new ArrayList<String>();
        update_times.add(modified_begin);
        update_times.add(modified_end);
        BasicCustomer r = basicCustomerService.getById(customerId);
        BasicWarehouse w = basicWarehouseService.getById(setWarehouseId);


        BasicPutgoods fh = basicPutgoodsService.getById(setUnitId);
        BasicAddressParam basicAddressParam = new BasicAddressParam();
        basicAddressParam.setPutgoodsId(Long.parseLong(fh.getId().toString()));
        BasicAddressResult addressResult = basicAddressService.findBySpec(basicAddressParam);
        if (addressResult == null) {
            return ResponseData.error("装货地址不存在！请维护");
        }

        if (ToolUtil.isNotEmpty(cover) && cover.equals("1")) {//清空待提交单据
            HxOrderOutParam orderOutParam1 = new HxOrderOutParam();
            orderOutParam1.setCustomerId(customerId);
            orderOutParam1.setSetWarehouseId(setWarehouseId);
            orderOutParam1.setSetUnitId(setUnitId);
            orderOutParam1.setOrderState("待提交");
            List<HxOrderOutResult> olist = hxOrderOutService.findOrderOutNumberListBySpec(orderOutParam1);
            if (olist.size() > 0) {
                List<Integer> deleteolist = new ArrayList<Integer>();
                List<String> deletedlist = new ArrayList<String>();
                for (HxOrderOutResult op : olist) {
                    deleteolist.add(op.getId());
                    deletedlist.add(op.getOrderOutNumber());
                }
                hxOrderOutService.deletebyids(deleteolist);
                hxOrderOutDetailedService.deletebyorders(deletedlist);
            }
        }

        JSONObject json = new JSONObject();
        int[] billType = {2001, 2003, 2006};
        json.put("entCode", "ENT136140");
        json.put("billType", billType);
        if (ToolUtil.isNotEmpty(r.getStoreIdXlb())) {
            json.put("organId", ListUtil.of(r.getStoreIdXlb().split(",")));
        }
        json.put("checkBeginDate", modified_begin);
        json.put("checkEndDate", modified_end);

        String post = HttpRequest.post(url)
                .body(json.toString()).execute().body();
        System.out.println("================json：" + json + "========================");
        System.out.println("================post：" + post + "========================");
        JSONObject jsonObject = new JSONObject(post);
        if (jsonObject.get("code").toString().equals("0")) {
            User user = userService.getcurrentUser();
            List<HxOrderOutParam> olist = new ArrayList<HxOrderOutParam>();//批量保存的 出库订单list
            List<HxOrderOutDetailedParam> detailedList = new ArrayList<HxOrderOutDetailedParam>();//批量保存的 订单商品明细list
            Long deptId = user.getDeptId();
            Long deliverId = user.getDeliverId();
            DealWithParam dealWithParam = new DealWithParam();
            dealWithParam.setNewCustomersflag(false);
            JSONArray jsonArray;
            try {
                jsonArray = new JSONArray(jsonObject.get("data").toString());
            } catch (Exception e) {
                return ResponseData.error("未拉取到数据");
            }


            BigDecimal as = new BigDecimal("0");
            Map<String, HxBasicGoodsResult> goodsMap = new HashMap<>();
            Map<String, String> oMap = new HashMap<>();
            if (jsonArray.length() > 0) {
                HxBasicGoodsParam hxgoodsp = new HxBasicGoodsParam();
                hxgoodsp.setGoodsCustomerId(r.getId());
                List<HxBasicGoodsResult> hxg = hxBasicGoodsService.findListBySpec(hxgoodsp);
                for (HxBasicGoodsResult gr : hxg) {
                    goodsMap.put(gr.getGoodsXlbId(), gr);
                }
                HxOrderOutParam hxop = new HxOrderOutParam();
                hxop.setCustomerId(customerId);
                List<HxOrderOutResult> hxoo = hxOrderOutService.findOrderListBySpec(hxop);
                for (HxOrderOutResult or : hxoo) {
                    oMap.put(or.getOrderOutNumber(), or.getOrderOutNumber());
                }
            }
            for (Object object : jsonArray) {
                JSONObject jsonObject2 = new JSONObject(object.toString());

                HxOrderOutParam opp = new HxOrderOutParam();
                //新增出库订单
                opp.setCustomerId(customerId);//客户id
                opp.setCustomerName(r.getCustomerName());//客户名称
                opp.setOrderState("待提交");//订单状态
                opp.setXlbSetUnitId(r.getStoreIdXlb());
                opp.setSetUnit(fh.getPutgoodsName());//装货单位
                opp.setSetUnitId(Long.parseLong(fh.getId().toString()));//装货单位id
                opp.setSetLocation(addressResult.getAddress());//装货地址
                opp.setSetLocationId(Long.parseLong(addressResult.getId().toString()));//装货地址id
                opp.setSetPeople(addressResult.getContacts());//联系人
                opp.setSetTel(addressResult.getTel());//联系电话
                opp.setXlbSetWarehouseId(w.getWarehouseXlbId());
                opp.setSetWarehouseId(setWarehouseId);//仓库id
                opp.setSetWarehouse(w.getWarehouseName());//仓库名称
                opp.setCreateUserName(user.getName());//制单人名称
                opp.setCreateTime(new Date());
                opp.setDeliverId(deliverId);//交付id
                opp.setDeptId(deptId);//部门id

                String fid = jsonObject2.get("sysBillCode").toString();
                if (ToolUtil.isNotEmpty(fid) && !fid.equals("null")) {//单据号
                    opp.setOrderOutNumber(fid);//订单号
                    //校验单号是否已添加
                    String orderOutNumber = oMap.get(fid);
                    if (orderOutNumber != null) {
                        continue;
                    }
                    //校验单号是否已存在 集合里
                    for (HxOrderOutParam opp2 : olist) {
                        if (opp2.getOrderOutNumber().equals(fid)) {
                            continue;
                        }
                    }
                } else {
                    continue;
                }

                String order_type_name = jsonObject2.get("billTypeName").toString();
                if (ToolUtil.isNotEmpty(order_type_name) && !order_type_name.equals("null")) {//出库单据类型
                    opp.setOrderType(order_type_name);
                }

//				String erp_order_types = jsonObject2.get("erp_order_types").toString();
//				if (ToolUtil.isNotEmpty(erp_order_types)&&!erp_order_types.equals("null")) {//关联单据类型
//					opp.setXlbRequestOrderType(erp_order_types);
//				}

                String delivery_date = jsonObject2.get("businessDate").toString();
                if (ToolUtil.isNotEmpty(delivery_date) && !delivery_date.equals("null")) {//配送日期
                    opp.setPeisongTime(delivery_date);
                }

//				String quantity1 = jsonObject2.get("quantity").toString();
//				if (ToolUtil.isNotEmpty(quantity1)&&!quantity1.equals("null")) {//申请数量
//					BigDecimal quantitybig1 = new BigDecimal(quantity1);
//					if(quantitybig1.compareTo(as) != 1) {
//						continue;
//					}
//				}
                if (jsonObject2.has("memo")) {
                    Object memo = jsonObject2.get("memo");
                    if (ToolUtil.isNotEmpty(memo) && !"null".equals(memo)) {//备注
                        opp.setNotes(EmojiTransferUtil.emojiEncode(memo.toString()));
                    }
                }
                String client_id = jsonObject2.get("otherOrganId").toString();
                if (ToolUtil.isNotEmpty(client_id) && !client_id.equals("null")) {//收货客户id
                    opp.setXlbClientId(client_id);
                }

//				String erp_client_id = jsonObject2.get("erp_client_id").toString();
//				if (ToolUtil.isNotEmpty(erp_client_id)&&!erp_client_id.equals("null")) {//erp收货客户id
//				}

                String client_name = jsonObject2.get("otherOrganName").toString();
                if (ToolUtil.isNotEmpty(client_name) && !client_name.equals("null")) {//客户名称
                    opp.setGetUnit(client_name);
                }

                String otherOrganType = jsonObject2.get("otherOrganType").toString();
                if (ToolUtil.isNotEmpty(otherOrganType) && !otherOrganType.equals("null")) {//收货客户类型
                    opp.setOutUnitType(otherOrganType);
                }


                JSONArray jsonArray2 = new JSONArray(jsonObject2.get("detailList").toString());
                if (jsonArray2.length() == 0) {
                    continue;
                }
                toDealWith4(opp, r, dealWithParam, client_id);//处理单位和地址

                int goodsCnt = 0;
                for (Object object2 : jsonArray2) {
                    JSONObject jsonObject3 = new JSONObject(object2.toString());

                    HxOrderOutDetailedParam hxd = new HxOrderOutDetailedParam();

                    String quantity = jsonObject3.get("amount").toString();
                    if (ToolUtil.isEmpty(quantity) || quantity.equals("null")) {//出库业务单位数量
                        continue;
                    }

                    String mainUnitAmount = jsonObject3.get("mainUnitAmount").toString();
                    if (ToolUtil.isEmpty(mainUnitAmount) || mainUnitAmount.equals("null")) {//最小单位出库数量
                        continue;
                    }
                    //限制仓库
                    if (jsonObject3.has("houseId") && ToolUtil.isNotEmpty(jsonObject3.get("houseId"))) {
                        if (ToolUtil.isNotEmpty(r.getXlbStorehouseId()) && !r.getXlbStorehouseId().equals(jsonObject3.get("houseId").toString())) {
                            continue;
                        }
                    }

//					String ratio = mainUnitAmount/quantity;
//					if (ToolUtil.isEmpty(ratio)||ratio.equals("null")) {//换算率
//						continue;
//					}

                    String unit = jsonObject3.get("unitName").toString();
                    if (ToolUtil.isEmpty(unit) || unit.equals("null")) {//单位
                        continue;
                    }

                    String item_code = jsonObject3.get("itemCode").toString();
                    if (ToolUtil.isEmpty(item_code) || item_code.equals("null")) {//商品代码
                        continue;
                    }

                    String item_id = jsonObject3.get("itemId").toString();
                    if (ToolUtil.isEmpty(item_id) || item_id.equals("null")) {//商品代码
                        continue;
                    }

                    HxBasicGoodsResult hxBasicGoodsResult = goodsMap.get(item_id);
                    if (hxBasicGoodsResult == null) {
                        return ResponseData.error(item_code + "商品不存在" + fid);
                    }

                    BigDecimal quantitybig = new BigDecimal(quantity);
                    BigDecimal mainUnitAmountbig = new BigDecimal(mainUnitAmount);
                    BigDecimal ratiobig = mainUnitAmountbig.divide(quantitybig, 3, BigDecimal.ROUND_HALF_DOWN);
//							BigDecimal psRate = new BigDecimal(hxBasicGoodsResult.getPsRate());
//							if(order_type_name.equals("采购退货")) {
//								if(psRate.compareTo(ratiobig) == -1) {
//									//如果配送换算率 小于 xlb换算率：  配送数量  =  xlb数量*（xlb换算率/配送换算率）
//									BigDecimal div = ratiobig.divide(psRate,3, BigDecimal.ROUND_HALF_DOWN);
//									BigDecimal divv_n = quantitybig.multiply(div).setScale(3, BigDecimal.ROUND_HALF_DOWN);
//									quantitybig = divv_n;
//									ratiobig = psRate;
//								}
//								if(psRate.compareTo(ratiobig) == 1) {
//									//如果配送换算率 大于 xlb换算率：  配送数量  =  xlb数量/（配送换算率/xlb换算率）
//									BigDecimal div = psRate.divide(ratiobig,3, BigDecimal.ROUND_HALF_DOWN);
//									BigDecimal divv_n = quantitybig.divide(div,3, BigDecimal.ROUND_HALF_DOWN);
//									quantitybig = divv_n;
//									ratiobig = psRate;
//								}
//							}
                    BigDecimal basicNum = quantitybig.multiply(ratiobig).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                    if (basicNum.compareTo(as) != 1) {
                        continue;
                    }
                    hxd.setXlbGoodsId(hxBasicGoodsResult.getGoodsXlbId());
                    hxd.setJibenNum(basicNum + "");
                    hxd.setJibenUnit(hxBasicGoodsResult.getJibenUnit());
                    BigDecimal psNum = new BigDecimal("0");
                    BigDecimal goodsVolume = new BigDecimal(hxBasicGoodsResult.getGoodsVolume());
                    BigDecimal goodsWeight = new BigDecimal(hxBasicGoodsResult.getGoodsWeight());
                    BigDecimal goodsPrice = new BigDecimal("0");

                    hxd.setUnit(unit);
                    hxd.setRate(ratiobig.toString());
                    BigDecimal jbRate = new BigDecimal("1");
                    BigDecimal cgRate = new BigDecimal(hxBasicGoodsResult.getCgRate());
//							if(psRate.compareTo(jbRate) == 1) {
//								psNum = basicNum.divide(psRate,3, BigDecimal.ROUND_HALF_DOWN);
//							} else {
//								psNum = basicNum;
//							}
//							if(psNum.compareTo(quantitybig) != 0) {
//								if(!order_type_name.equals("采购退货")) {
//									return ResponseData.error(fid+"中"+item_code+"商品计算时出错，请检查换算率！");
//								}
//							}
                    if (ratiobig.compareTo(cgRate) == -1) {
                        //如果配送换算率 小于 采购换算率：  配送体积  =  采购体积/（采购换算率/配送换算率）
                        BigDecimal div = cgRate.divide(ratiobig, 3, BigDecimal.ROUND_HALF_DOWN);
                        BigDecimal divv_v = goodsVolume.divide(div, 4, BigDecimal.ROUND_HALF_DOWN);
                        goodsVolume = divv_v;
                        BigDecimal divv_w = goodsWeight.divide(div, 3, BigDecimal.ROUND_HALF_DOWN);
                        goodsWeight = divv_w;
                    }
                    if (ratiobig.compareTo(cgRate) == 1) {
                        //如果配送换算率 大于 采购换算率：  配送体积  =  采购体积*（配送换算率/采购换算率）
                        BigDecimal div = ratiobig.divide(cgRate, 3, BigDecimal.ROUND_HALF_DOWN);
                        BigDecimal divv_v = goodsVolume.multiply(div).setScale(4, BigDecimal.ROUND_HALF_DOWN);
                        goodsVolume = divv_v;
                        BigDecimal divv_w = goodsWeight.multiply(div).setScale(3, BigDecimal.ROUND_HALF_DOWN);
                        goodsWeight = divv_w;
                    }
                    BigDecimal goodsChargingPs = new BigDecimal(hxBasicGoodsResult.getGoodsChargingPs());
                    goodsPrice = ratiobig.multiply(goodsChargingPs).setScale(3, BigDecimal.ROUND_HALF_DOWN);

                    //创建订单明细
                    hxd.setOrderOutNumber(fid);
                    hxd.setGoodsId(Long.parseLong(hxBasicGoodsResult.getId().toString()));
                    hxd.setGoodsName(hxBasicGoodsResult.getGoodsName());
                    hxd.setGoodsNumber(hxBasicGoodsResult.getGoodsNumber());
                    hxd.setGoodsPcode69(hxBasicGoodsResult.getGoodsPcode69());
                    hxd.setGoodsXcode69(hxBasicGoodsResult.getGoodsXcode69());
                    hxd.setGoodsHcode69(hxBasicGoodsResult.getGoodsHcode69());
                    hxd.setGoodsSpecs(hxBasicGoodsResult.getGoodsSpecs());
                    hxd.setDismantlingParts(hxBasicGoodsResult.getDismantlingParts());

                    hxd.setPsNum(quantity);

                    hxd.setGoodsWeight(goodsWeight.toString());
                    hxd.setOutWeight(quantitybig.multiply(goodsWeight).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
                    hxd.setGoodsVolume(goodsVolume.toString());
                    hxd.setOutVolume(quantitybig.multiply(goodsVolume).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());

                    if (jsonObject3.has("detailMemo")) {
                        Object detailMemo = jsonObject3.get("detailMemo");
                        if (ToolUtil.isNotEmpty(detailMemo) && !"null".equals(detailMemo)) {//明细备注
                            hxd.setNotes(detailMemo.toString());
                        }
                    }

//					hxd.setGoodsPrice(goodsPrice.toString());
//					hxd.setOutMoney(quantitybig.multiply(goodsPrice).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
                    // 单价
                    Object salesTaxPrice = jsonObject3.get("salesTaxPrice");
                    if (ToolUtil.isNotEmpty(salesTaxPrice) && !"null".equals(salesTaxPrice)) {
                        hxd.setGoodsPrice(salesTaxPrice.toString());
                    }
                    //单价总额
                    Object salesTaxMoney = jsonObject3.get("salesTaxMoney");
                    if (ToolUtil.isNotEmpty(salesTaxMoney) && !"null".equals(salesTaxMoney)) {
                        hxd.setOutMoney(salesTaxMoney.toString());
                    }

                    //入库仓库名称
                    if (jsonObject3.has("inHouseName")) {
                        Object inHouseName = jsonObject3.get("inHouseName");
                        if (ToolUtil.isNotEmpty(inHouseName) && !"null".equals(inHouseName)) {
                            hxd.setGetUnit(inHouseName.toString());
                            opp.setGetUnitRemark(inHouseName.toString());
                        }
                    }

                    //入库仓库名称
                    if (jsonObject3.has("inHouseId")) {
                        Object inHouseId = jsonObject3.get("inHouseId");
                        if (ToolUtil.isNotEmpty(inHouseId) && !"null".equals(inHouseId)) {
                            hxd.setGetUnitId(Long.valueOf(inHouseId.toString()));
                        }
                    }
                    detailedList.add(hxd);
                    goodsCnt++;
//					hxd = new HxOrderOutDetailedParam();
                }
                if (goodsCnt > 0) {
                    olist.add(opp);
                }
                if (olist.size() == 40 && detailedList.size() > 0) {
                    hxOrderOutService.saveBatchList(olist);
                    if (detailedList.size() > 0) {
                        hxOrderOutDetailedService.saveBatchList(detailedList);
                    }
                    olist = new ArrayList<HxOrderOutParam>();
                    detailedList = new ArrayList<HxOrderOutDetailedParam>();
                }
            }
            if (olist.size() > 0 && detailedList.size() > 0) {
                hxOrderOutService.saveBatchList(olist);
                if (detailedList.size() > 0) {
                    hxOrderOutDetailedService.saveBatchList(detailedList);
                }
            }
            data.setSuccess(true);
            if (dealWithParam.isNewCustomersflag()) {
                data.setCode(450);
                data.setMessage(dealWithParam.getNewCustomers().replaceAll("null", ""));
            }
        } else {
            String msg = jsonObject.get("msg").toString();
            return ResponseData.error(msg);
        }

        return ResponseData.success();
    }

    @Autowired
    private BasicXlbOauth2tokenService basicXlbOauth2tokenService;

    @Autowired
    private BasicAddressService basicAddressService;

    @Autowired
    private HxBasicGoodsService hxBasicGoodsService;

    @Autowired
    private HxBasicUnitCodeService hxBasicUnitCodeService;

    private void toDealWith3(HxOrderOutParam opp, BasicCustomer basicCustomer,
                             DealWithParam dealWithParam, String oauth2TokenXlb, String client_id, String erp_client_id) {
        User user = userService.getcurrentUser();
        //查询卸货单位 是否存在
        BasicPutgoods bpgp3 = new BasicPutgoods();
        bpgp3.setPutgoodsCustomerId(basicCustomer.getId());//客户id
        bpgp3.setPutgoodsName(opp.getGetUnit());//单位名称 
        BasicPutgoods bputr2 = basicPutgoodsService.lambdaQuery()
                .eq(BasicPutgoods::getPutgoodsCustomerId, basicCustomer.getId())
                .eq(BasicPutgoods::getPutgoodsName, opp.getGetUnit())
//        .eq(BasicPutgoods::getXlbClientId, client_id)
                .last("LIMIT 1")
                .one();
        if (bputr2 == null) {
            boolean mendian = false;
            bpgp3.setPutgoodsOperateName(basicCustomer.getCustomerName());//客户名称
            bpgp3.setXlbClientId(client_id);
            bpgp3.setUnitType("门店");
            bpgp3.setDictId(0l);
            bpgp3.setDeliverId(user.getDeliverId());
            bpgp3.setDeptId(user.getDeptId());
            if (ToolUtil.isNotEmpty(opp.getOrderType())) {
                if (opp.getOrderType().equals("批发销售")) {
                    bpgp3.setUnitType("批发客户");
                } else if (opp.getOrderType().equals("采购退货")) {
                    bpgp3.setUnitType("供应商");
                } else if (opp.getOrderType().equals("仓间调拨")) {
                    bpgp3.setUnitType("配送中心");
                } else if (opp.getOrderType().equals("门店调出")) {
                    mendian = true;
//                    String url = "https://test-api.xlbsoft.com/api/hxl.open.store.read";
                    String url = "https://hxl-api.xlbsoft.com/api/hxl.open.store.read";

                    JSONObject json = new JSONObject();
                    json.put("id", erp_client_id);
                    String post = HttpRequest.post(url)
                            .header("Authorization", "bearer " + oauth2TokenXlb).body(json.toString()).execute().body();
//	       			System.out.println("================json："+json+"========================");
//	       			System.out.println("================post："+post+"========================");

                    JSONObject jsonObject = new JSONObject(post);
                    if (jsonObject.get("code").toString().equals("0")) {
                        JSONObject jsonObject2 = new JSONObject(jsonObject.get("data").toString());
                        String store_group_id = jsonObject2.get("store_group_id").toString();
                        if (ToolUtil.isNotEmpty(store_group_id) && !store_group_id.equals("null")) {//门店分组id
                            if (store_group_id.equals("0")) {
                                bpgp3.setDictId(0l);
                            } else {
                                HxBasicUnitCodeParam basicUnitCodeParam = new HxBasicUnitCodeParam();
                                basicUnitCodeParam.setV1("门店");
                                basicUnitCodeParam.setXlbStoreGroupId(store_group_id);
                                basicUnitCodeParam.setDeptId(user.getDeptId());
                                basicUnitCodeParam.setOperateId(user.getOperateId());
                                HxBasicUnitCodeResult codeResult = hxBasicUnitCodeService.findBySpec(basicUnitCodeParam);
                                if (codeResult != null) {
                                    bpgp3.setDictId(Long.parseLong(codeResult.getId() + ""));
                                }
                            }
                        }

                        basicPutgoodsService.save(bpgp3);
                        opp.setGetUnitId(Long.parseLong(bpgp3.getId().toString()));//卸货单位id
                        dealWithParam.setNewCustomersflag(true);
                        dealWithParam.setNewCustomers(dealWithParam.getNewCustomers() + "新收货单位：" + opp.getGetUnit() + "；");

                        BasicAddress bap3 = new BasicAddress();
                        bap3.setPutgoodsName(opp.getGetUnit());
                        bap3.setPutgoodsId(Long.parseLong(bpgp3.getId().toString()));

                        String address = jsonObject2.get("address").toString();
                        if (ToolUtil.isNotEmpty(address) && !address.equals("null")) {//地址
                            bap3.setAddress(address);
                        }

                        String tel = jsonObject2.get("tel").toString();
                        if (ToolUtil.isNotEmpty(tel) && !tel.equals("null")) {//电话
                            bap3.setTel(tel);
                        }

                        String contact = jsonObject2.get("contact").toString();
                        if (ToolUtil.isNotEmpty(contact) && !contact.equals("null")) {//联系人
                            bap3.setContacts(contact);
                        }

                        String province = jsonObject2.get("province").toString();
                        if (ToolUtil.isNotEmpty(province) && !province.equals("null")) {//省
                            bap3.setSheng(province);
                        }

                        String city = jsonObject2.get("city").toString();
                        if (ToolUtil.isNotEmpty(city) && !city.equals("null")) {//市
                            bap3.setShi(city);
                        }

                        String district = jsonObject2.get("district").toString();
                        if (ToolUtil.isNotEmpty(district) && !district.equals("null")) {//区
                            bap3.setQu(district);
                        }

                        String street = jsonObject2.get("street").toString();
                        if (ToolUtil.isNotEmpty(street) && !street.equals("null")) {//街道
                            bap3.setJie(street);
                        }
                        bap3.setLongitude("0");
                        bap3.setLatitude("0");
                        bap3.setSwitchWl("1");
                        bap3.setSwitchBj("1500");//提货围栏半径 默认100米
                        bap3.setSwitchBj2("2000");//收货围栏半径 默认100米
                        basicAddressService.save(bap3);
                        opp.setGetLocationId(Long.parseLong(bap3.getId().toString()));//卸货地址id
                        opp.setGetLocation(bap3.getAddress());//卸货地址
                        opp.setGetPeople(bap3.getContacts());//联系人
                        opp.setGetTel(bap3.getTel());//联系电话
                    }
                }
            }
            if (!mendian) {
                basicPutgoodsService.save(bpgp3);
                opp.setGetUnitId(Long.parseLong(bpgp3.getId().toString()));//卸货单位id
                dealWithParam.setNewCustomersflag(true);
                dealWithParam.setNewCustomers(dealWithParam.getNewCustomers() + "新收货单位：" + opp.getGetUnit() + "；");

                BasicAddress bap3 = new BasicAddress();
                bap3.setPutgoodsName(opp.getGetUnit());
                bap3.setPutgoodsId(Long.parseLong(bpgp3.getId().toString()));
                bap3.setAddress(opp.getGetUnit());
                bap3.setLongitude("0");
                bap3.setLatitude("0");
                bap3.setSwitchWl("1");
                bap3.setSwitchBj("1500");//提货围栏半径 默认100米
                bap3.setSwitchBj2("2000");//收货围栏半径 默认100米
                basicAddressService.save(bap3);
                opp.setGetLocationId(Long.parseLong(bap3.getId().toString()));//卸货地址id
                opp.setGetLocation(bap3.getAddress());//卸货地址
            }
        } else {
            if (ToolUtil.isEmpty(bputr2.getXlbClientId())) {
                if (ToolUtil.isNotEmpty(client_id)) {
                    BasicPutgoods bd = new BasicPutgoods();
                    bd.setId(bputr2.getId());
                    bd.setXlbClientId(client_id);
                    basicPutgoodsService.updateById(bd);
                }
            }

            opp.setGetUnit(bputr2.getPutgoodsName());//卸货单位
            opp.setGetUnitId(Long.parseLong(bputr2.getId().toString()));//卸货单位id
            //查询卸货地点 是否存在
            BasicAddress bap3 = new BasicAddress();
            bap3.setPutgoodsId(Long.parseLong(bputr2.getId().toString()));//单位id
            BasicAddress bar2 = basicAddressService.lambdaQuery()
                    .eq(BasicAddress::getPutgoodsId, bputr2.getId())
                    .last("LIMIT 1")
                    .one();
            if (bar2 != null) {
                opp.setGetLocationId(Long.parseLong(bar2.getId().toString()));//卸货地址id
                opp.setGetLocation(bar2.getAddress());//卸货地址
                opp.setGetPeople(bar2.getContacts());//联系人
                opp.setGetTel(bar2.getTel());//联系电话
            } else {//如果没有地址
                bap3.setAddress(bputr2.getPutgoodsName());//地点 为单位名称
                bap3.setPutgoodsName(bputr2.getPutgoodsName());//单位名称
                bap3.setLongitude("0");
                bap3.setLatitude("0");
                bap3.setSwitchWl("1");
                bap3.setSwitchBj("1500");//提货围栏半径 默认100米
                bap3.setSwitchBj2("2000");//收货围栏半径 默认100米
                basicAddressService.save(bap3);
                opp.setGetLocation(bap3.getAddress());//卸货地址
                opp.setGetLocationId(Long.parseLong(bap3.getId().toString()));//卸货地址id
            }
        }
    }

    /**
     * 导入页面
     */
    @RequestMapping("/toimportExcel")
    public String toimportExcel(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId, deliverId, user.getOperateId()));

        //查询可选择仓库
        model.addAttribute("wlist", basicWarehouseService.findAvailableList(deptId, deliverId, user.getOperateId()));

        BasicPutgoodsParam basicPutgoodsParam = new BasicPutgoodsParam();
        basicPutgoodsParam.setUnitCategory("发货");
        basicPutgoodsParam.setUnitType("配送中心");
        basicPutgoodsParam.setDeptId(deptId);
        List<BasicPutgoodsResult> pglist = basicPutgoodsService.findListBySpec(basicPutgoodsParam, user.getOperateId());
        model.addAttribute("pglist", pglist);
        return PREFIX + "/import.html";
    }

    /**
     * 导入页面
     */
    @RequestMapping("/toduoDianImportExcel")
    public String toduoDianImportExcel(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId, deliverId, user.getOperateId()));

        //查询可选择仓库
        model.addAttribute("wlist", basicWarehouseService.findAvailableList(deptId, deliverId, user.getOperateId()));

        BasicPutgoodsParam basicPutgoodsParam = new BasicPutgoodsParam();
        basicPutgoodsParam.setUnitCategory("发货");
        basicPutgoodsParam.setUnitType("配送中心");
        basicPutgoodsParam.setDeptId(deptId);
        List<BasicPutgoodsResult> pglist = basicPutgoodsService.findListBySpec(basicPutgoodsParam, user.getOperateId());
        model.addAttribute("pglist", pglist);
        return PREFIX + "/duodianImport.html";
    }

    /**
     * 上传excel
     */
    @RequestMapping(value = "/importDuoDianExcel", method = {RequestMethod.POST})
    @ResponseBody
    public ResponseData importDuoDianExcel(@RequestPart("file") MultipartFile file, HxOrderOutParam hxOrderOutParam) {
        ResponseData data = new ResponseData();
        if (hxOrderOutParam.getSetWarehouseId() == null || hxOrderOutParam.getCustomerId() == null || hxOrderOutParam.getSetUnitId() == null) {
            data.setSuccess(false);
            data.setMessage("请填写订单基本信息!");
            return data;
        }
        lock.lock();//获取锁
        try {
            data = hxOrderOutService.getDuoDianExceldata(file, hxOrderOutParam, data);//处理导入数据
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//释放锁
        }
        return data;
    }

    /**
     * 上传excel
     */
    @RequestMapping(value = "/importExceNewmethodl", method = {RequestMethod.POST})
    @ResponseBody
    public ResponseData importExceNewmethodl(@RequestPart("file") MultipartFile file, HxOrderOutParam hxOrderOutParam) {
        ResponseData data = new ResponseData();
        if (hxOrderOutParam.getSetWarehouseId() == null || hxOrderOutParam.getCustomerId() == null || hxOrderOutParam.getSetUnitId() == null) {
            data.setSuccess(false);
            data.setMessage("请填写订单基本信息!");
            return data;
        }
        lock.lock();//获取锁
        try {
            data = hxOrderOutService.getExceldata(file, hxOrderOutParam, data);//处理导入数据
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//释放锁
        }
        return data;
    }

    /**
     * 下载入库订单模板
     *
     * @throws ServletException , IOException
     */
    @RequestMapping("downloadExcelTemplate")
    public void downloadExcelTemplate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = "assets/excel/hxorderOut.xlsx";
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
            OutputStream outputStream = response.getOutputStream();
            //设置下载的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("零售出库订单模板" + ".xlsx").getBytes(), "iso-8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载多点出库订单模板
     *
     * @throws ServletException , IOException
     */
    @RequestMapping("downloadDuoDianExcelTemplate")
    public void downloadDuoDianExcelTemplate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = "assets/excel/khOutOrder.xlsx";
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
            OutputStream outputStream = response.getOutputStream();
            //设置下载的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("多点出库订单模板" + ".xlsx").getBytes(), "iso-8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 新增页面
     *
     * @author zhucx
     * @Date 2023-08-30
     */
    @RequestMapping("/add")
    public String add(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择仓库
        model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId, deliverId, user.getOperateId()));
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId, deliverId, user.getOperateId()));

        BasicPutgoodsParam basicPutgoodsParam = new BasicPutgoodsParam();
        basicPutgoodsParam.setUnitCategory("发货");
        basicPutgoodsParam.setUnitType("配送中心");
        basicPutgoodsParam.setDeptId(deptId);
        List<BasicPutgoodsResult> pglist = basicPutgoodsService.findListBySpec(basicPutgoodsParam, user.getOperateId());
        model.addAttribute("pglist", pglist);
        return PREFIX + "/hxOrderOut_add.html";
    }

    /**
     * 编辑页面
     *
     * @author zhucx
     * @Date 2023-08-30
     */
    @RequestMapping("/edit")
    public String edit(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择仓库
        model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId, deliverId, user.getOperateId()));
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId, deliverId, user.getOperateId()));

        BasicPutgoodsParam basicPutgoodsParam = new BasicPutgoodsParam();
        basicPutgoodsParam.setUnitCategory("发货");
        basicPutgoodsParam.setUnitType("配送中心");
        basicPutgoodsParam.setDeptId(deptId);
        List<BasicPutgoodsResult> pglist = basicPutgoodsService.findListBySpec(basicPutgoodsParam, user.getOperateId());
        model.addAttribute("pglist", pglist);
        return PREFIX + "/hxOrderOut_edit.html";
    }

    @Autowired
    private DeptService deptService;

    /**
     * 获取所属项目单号前缀
     *
     * @param user
     * @return
     */
    public String getOperateIdOrderPrefix(User user) {
        if (user.getOperateId() != null) {
            Dept dept = new Dept();
            dept.setOperateId(user.getOperateId());
            Dept resdept = deptService.findBySpec(dept);
            if (resdept != null) {
                if (ToolUtil.isNotEmpty(resdept.getOrderPrefix())) {
                    return resdept.getOrderPrefix();
                } else {
                    return user.getAccount().substring(0, 3);
                }
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * 新增接口
     *
     * @author zhucx
     * @Date 2023-08-30
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(HxOrderOutParam hxOrderOutParam) {
        User user = userService.getcurrentUser();
        String trayCode = getOperateIdOrderPrefix(user);
        if (ToolUtil.isNotEmpty(hxOrderOutParam.getOrderOutNumber())) {
            //校验客户单号 是否存在
            if (this.hxOrderOutService.checkCustomerOrder(hxOrderOutParam.getOrderOutNumber())) {
                return ResponseData.error("单号已存在");
            }
        } else {
            hxOrderOutParam.setOrderOutNumber(trayCode + "CK" + DateUtil.getDatesBch() + DateUtil.getRandomNumber());
        }
        Object WarehouseId = hxOrderOutParam.getSetWarehouseId();
        if (WarehouseId != null) {
            BasicWarehouse bawBasicWarehouse = basicWarehouseService.getById(Integer.parseInt(WarehouseId.toString()));
            hxOrderOutParam.setSetWarehouse(bawBasicWarehouse.getWarehouseName());//set 仓库名称
        }
        Object CustomerId = hxOrderOutParam.getCustomerId();
        if (CustomerId != null) {
            BasicCustomer basicCustomer = basicCustomerService.getById(Integer.parseInt(CustomerId.toString()));
            hxOrderOutParam.setCustomerName(basicCustomer.getCustomerName());//set 客户名称
        }
        Object setUnitId = hxOrderOutParam.getSetUnitId();
        if (setUnitId != null) {
            BasicPutgoods basicPutgoods = basicPutgoodsService.getById(Integer.parseInt(setUnitId.toString()));
            hxOrderOutParam.setSetUnit(basicPutgoods.getPutgoodsName());
        }
        hxOrderOutParam.setDeptId(user.getDeptId());
        hxOrderOutParam.setDeliverId(user.getDeliverId());
        hxOrderOutParam.setOrderState("待提交");//set 单据状态
        hxOrderOutParam.setCreateUserName(user.getName());//set 制单用户名称
        this.hxOrderOutService.add(hxOrderOutParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author zhucx
     * @Date 2023-08-30
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(HxOrderOutParam hxOrderOutParam) {
        //校验客户单号 是否存在
        HxOrderOut hxOrderOut = this.hxOrderOutService.getById(hxOrderOutParam.getId());
        if (!hxOrderOut.getOrderOutNumber().equals(hxOrderOutParam.getOrderOutNumber())) {
            if (this.hxOrderOutService.checkCustomerOrder(hxOrderOutParam.getOrderOutNumber())) {
                return ResponseData.error("单号已存在");
            }
        }
        Object WarehouseId = hxOrderOutParam.getSetWarehouseId();
        if (WarehouseId != null) {
            BasicWarehouse bawBasicWarehouse = basicWarehouseService.getById(Integer.parseInt(WarehouseId.toString()));
            hxOrderOutParam.setSetWarehouse(bawBasicWarehouse.getWarehouseName());//set 仓库名称
        }
        Object CustomerId = hxOrderOutParam.getCustomerId();
        if (CustomerId != null) {
            BasicCustomer basicCustomer = basicCustomerService.getById(Integer.parseInt(CustomerId.toString()));
            hxOrderOutParam.setCustomerName(basicCustomer.getCustomerName());//set 客户名称
        }
        Object setUnitId = hxOrderOutParam.getSetUnitId();
        if (setUnitId != null) {
            BasicPutgoods basicPutgoods = basicPutgoodsService.getById(Integer.parseInt(setUnitId.toString()));
            hxOrderOutParam.setSetUnit(basicPutgoods.getPutgoodsName());
        }
        this.hxOrderOutService.update(hxOrderOutParam);
        return ResponseData.success();
    }

    /**
     * 批量作废
     */
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping("/tovoid")
    @ResponseBody
    public ResponseData tovoid(@RequestParam("ids") Long[] ids) {
        for (Long id : ids) {
            HxOrderOut hxOrderOut = this.hxOrderOutService.getById(id);
            if (hxOrderOut.getOrderState().equals("撤回") || hxOrderOut.getOrderState().equals("待提交")) {
                HxOrderOutParam param = new HxOrderOutParam();
                param.setOrderState("作废");
                param.setId(Integer.parseInt(id.toString()));
                hxOrderOutService.update(param);
            }
        }
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author zhucx
     * @Date 2023-08-30
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(HxOrderOutParam hxOrderOutParam) {
        this.hxOrderOutService.delete(hxOrderOutParam);
        return ResponseData.success();
    }

    /**
     * 批量删除
     */
    @RequestMapping("/btnDelete")
    @ResponseBody
    public ResponseData btnDelete(Long ids[]) {
        for (Long id : ids) {
            HxOrderOut hxOrderOut = hxOrderOutService.getById(id);
            if (hxOrderOut.getOrderState().equals("作废")) {
                HxOrderOutDetailedParam detailedParam = new HxOrderOutDetailedParam();
                detailedParam.setOrderOutNumber(hxOrderOut.getOrderOutNumber());
                hxOrderOutDetailedService.deleteBySpec(detailedParam);

                HxOrderOutParam hxOrderOutParam = new HxOrderOutParam();
                hxOrderOutParam.setId(hxOrderOut.getId());
                this.hxOrderOutService.delete(hxOrderOutParam);
            } else {
                return ResponseData.error("只可删除作废订单");
            }
        }
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author zhucx
     * @Date 2023-08-30
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(HxOrderOutParam hxOrderOutParam) {
        HxOrderOut detail = this.hxOrderOutService.getById(hxOrderOutParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @throws UnsupportedEncodingException
     * @author zhucx
     * @Date 2023-08-30
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(HxOrderOutParam hxOrderOutParam, String condition, String startTime, String endTime) throws UnsupportedEncodingException {
        User user = userService.getcurrentUser();
        hxOrderOutParam.setDeptId(user.getDeptId());
        if (ToolUtil.isEmpty(hxOrderOutParam.getTimeType())) {
            hxOrderOutParam.setTimeType("cj");
        }
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            hxOrderOutParam.setTimeInterval("'" + startTime + "' and '" + endTime + "'");
        } else if (startTime == null && endTime == null) {
            hxOrderOutParam.setTimeInterval("'" + DateUtil.getDate() + "' and '" + DateUtil.getDate() + "'");
        }
        LayuiPageInfo layuiPageInfo = this.hxOrderOutService.findPageBySpec(hxOrderOutParam, condition, user.getOperateId());
        List<HxOrderOutResult> list = layuiPageInfo.getData();
        for (HxOrderOutResult r : list) {
            if (ToolUtil.isNotEmpty(r.getNotes())) {
                r.setNotes(EmojiTransferUtil.emojiDecode(r.getNotes()));
            }
        }
        layuiPageInfo.setData(list);
        return layuiPageInfo;
    }

    /**
     * 查询列表
     *
     * @throws UnsupportedEncodingException
     * @author zhucx
     * @Date 2023-08-30
     */
    @ResponseBody
    @RequestMapping("/querylist")
    public LayuiPageInfo querylist(HxOrderOutParam hxOrderOutParam, String condition, String startTime, String endTime) throws UnsupportedEncodingException {
        User user = userService.getcurrentUser();
        hxOrderOutParam.setDeptId(user.getDeptId());
        if (ToolUtil.isEmpty(hxOrderOutParam.getTimeType())) {
            hxOrderOutParam.setTimeType("cj");
        }
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            hxOrderOutParam.setTimeInterval("'" + startTime + "' and '" + endTime + "'");
        } else if (startTime == null && endTime == null) {
            hxOrderOutParam.setTimeInterval("'" + DateUtil.getDate() + "' and '" + DateUtil.getDate() + "'");
        }
        LayuiPageInfo layuiPageInfo = this.hxOrderOutService.findqueryPageBySpec(hxOrderOutParam, condition, user.getOperateId());
        List<HxOrderOutResult> list = layuiPageInfo.getData();
        for (HxOrderOutResult r : list) {
            if (ToolUtil.isNotEmpty(r.getNotes())) {
                r.setNotes(EmojiTransferUtil.emojiDecode(r.getNotes()));
            }
        }
        layuiPageInfo.setData(list);
        return layuiPageInfo;
    }

    /**
     * 撤回
     */
    @RequestMapping("/revoke")
    @ResponseBody
    public ResponseData revoke(HxOrderOutParam hxOrderOutParam) {
        ResponseData data = new ResponseData();
        HxOrderOut hxOrderOut = hxOrderOutService.getById(hxOrderOutParam.getId());
        if ("已生成".equals(hxOrderOut.getOrderState())) {
            data = hxOrderOutService.revoke(hxOrderOut, data);
        } else {
            data.setMessage("已完成出库无法撤回");
            data.setSuccess(false);
        }
        return data;
    }

    /**
     * 合计
     */
    @ResponseBody
    @RequestMapping("/count")
    public ResponseData count(HxOrderOutParam hxOrderOutParam, String condition, String startTime, String endTime) {
        User user = userService.getcurrentUser();
        hxOrderOutParam.setDeptId(user.getDeptId());
        hxOrderOutParam.setDeliverId(user.getDeliverId());
        if (ToolUtil.isEmpty(hxOrderOutParam.getTimeType())) {
            hxOrderOutParam.setTimeType("cj");
        }
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            hxOrderOutParam.setTimeInterval("'" + startTime + "' and '" + endTime + "'");
        } else if (startTime == null && endTime == null) {
            hxOrderOutParam.setTimeInterval("'" + DateUtil.getDate() + "' and '" + DateUtil.getDate() + "'");
        }
        return ResponseData.success(this.hxOrderOutService.count(hxOrderOutParam, condition, user.getOperateId()));

    }

    /**
     * 导出
     */
    @ResponseBody
    @RequestMapping("/listAll")
    public List<HxOrderOutResult> listAll(HxOrderOutParam hxOrderOutParam, String condition, String startTime, String endTime) {
        User user = userService.getcurrentUser();
        hxOrderOutParam.setDeptId(user.getDeptId());
        hxOrderOutParam.setDeliverId(user.getDeliverId());
        if (ToolUtil.isEmpty(hxOrderOutParam.getTimeType())) {
            hxOrderOutParam.setTimeType("cj");
        }
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            hxOrderOutParam.setTimeInterval("'" + startTime + "' and '" + endTime + "'");
        } else if (startTime == null && endTime == null) {
            hxOrderOutParam.setTimeInterval("'" + DateUtil.getDate() + "' and '" + DateUtil.getDate() + "'");
        }
        return this.hxOrderOutService.findlistAllBySpec(hxOrderOutParam, condition, user.getOperateId());
    }

    /**
     * 导出
     */
    @ResponseBody
    @RequestMapping("/listAll1")
    public List<HxOrderOutResult> listAll1(HxOrderOutParam hxOrderOutParam, String condition, String startTime, String endTime) {
        User user = userService.getcurrentUser();
        hxOrderOutParam.setDeptId(user.getDeptId());
        hxOrderOutParam.setDeliverId(user.getDeliverId());
        if (ToolUtil.isEmpty(hxOrderOutParam.getTimeType())) {
            hxOrderOutParam.setTimeType("cj");
        }
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            hxOrderOutParam.setTimeInterval("'" + startTime + "' and '" + endTime + "'");
        } else if (startTime == null && endTime == null) {
            hxOrderOutParam.setTimeInterval("'" + DateUtil.getDate() + "' and '" + DateUtil.getDate() + "'");
        }
        return this.hxOrderOutService.findlistAllBySpec1(hxOrderOutParam, condition, user.getOperateId());
    }

    /**
     * 合计
     */
    @ResponseBody
    @RequestMapping("/count1")
    public ResponseData count1(HxOrderOutParam hxOrderOutParam, String condition, String startTime, String endTime) {
        User user = userService.getcurrentUser();
        hxOrderOutParam.setDeptId(user.getDeptId());
        hxOrderOutParam.setDeliverId(user.getDeliverId());
        if (ToolUtil.isEmpty(hxOrderOutParam.getTimeType())) {
            hxOrderOutParam.setTimeType("cj");
        }
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            hxOrderOutParam.setTimeInterval("'" + startTime + "' and '" + endTime + "'");
        } else if (startTime == null && endTime == null) {
            hxOrderOutParam.setTimeInterval("'" + DateUtil.getDate() + "' and '" + DateUtil.getDate() + "'");
        }
        return ResponseData.success(this.hxOrderOutService.count1(hxOrderOutParam, condition, user.getOperateId()));

    }


    private void toDealWith4(HxOrderOutParam opp, BasicCustomer basicCustomer,
                             DealWithParam dealWithParam, String client_id) {
        User user = userService.getcurrentUser();
        //查询卸货单位 是否存在
        BasicPutgoods bpgp3 = new BasicPutgoods();
        bpgp3.setPutgoodsCustomerId(basicCustomer.getId());//客户id
        bpgp3.setPutgoodsName(opp.getGetUnit());//单位名称
        BasicPutgoods bputr2 = basicPutgoodsService.lambdaQuery()
                .eq(BasicPutgoods::getPutgoodsCustomerId, basicCustomer.getId())
                .eq(BasicPutgoods::getPutgoodsName, opp.getGetUnit())
//        .eq(BasicPutgoods::getXlbClientId, client_id)
                .last("LIMIT 1")
                .one();
        if (bputr2 == null) {
            boolean mendian = false;
            bpgp3.setPutgoodsOperateName(basicCustomer.getCustomerName());//客户名称
            bpgp3.setXlbClientId(client_id);
            bpgp3.setUnitType("门店");
            bpgp3.setDictId(0l);
            bpgp3.setDeliverId(user.getDeliverId());
            bpgp3.setDeptId(user.getDeptId());
            if (ToolUtil.isNotEmpty(opp.getOutUnitType())) {
                if (opp.getOutUnitType().equals("1")) {
                    bpgp3.setUnitType("配送中心");
                } else if (opp.getOutUnitType().equals("5")) {
                    bpgp3.setUnitType("供应商");
                } else if (opp.getOutUnitType().equals("6")) {
                    bpgp3.setUnitType("客户");
                } else if (opp.getOutUnitType().equals("2")) {//门店
                    mendian = true;
                    String url = "https://tcsl.engine.fxscm.net/business/standard/api/v1/organ/shop";

                    JSONObject json = new JSONObject();
                    json.put("entCode", "ENT136140");
                    String post = HttpRequest.post(url)
                            .body(json.toString()).execute().body();
//	       			System.out.println("================json："+json+"========================");
//	       			System.out.println("================post："+post+"========================");

                    JSONObject jsonObject = new JSONObject(post);
//					AtomicReference<String> tel = new AtomicReference<>("");
//					AtomicReference<String> address = new AtomicReference<>("");
//					if(jsonObject.get("code").toString().equals("0")) {
////						JSONObject jsonObject2 = new JSONObject(jsonObject.get("data").toString());
//						JSONArray jsonArray = new JSONArray(jsonObject.get("data").toString());
//						jsonArray.forEach(obj -> {
//							JSONObject obj2 = (JSONObject) obj;
//							String store_id = obj2.get("id").toString();
//							if (ToolUtil.isNotEmpty(store_id)&&!store_id.equals("null")) {//门店id
//								if(store_id.equals(client_id)) {
//									if(ToolUtil.isNotEmpty(obj2.get("address"))&&obj2.get("address")!= null){
//										address.set(obj2.get("address").toString());
//									}
//									if(ToolUtil.isNotEmpty(obj2.get("phone"))&&obj2.get("phone")!= null){
//										tel.set(obj2.get("phone").toString());
//									}
//								}
//							}
//						});
//						String store_group_id = jsonObject2.get("store_group_id").toString();
//						if (ToolUtil.isNotEmpty(store_group_id)&&!store_group_id.equals("null")) {//门店分组id
//							if(store_group_id.equals("0")) {
//								bpgp3.setDictId(0l);
//							} else {
//								HxBasicUnitCodeParam basicUnitCodeParam = new HxBasicUnitCodeParam();
//								basicUnitCodeParam.setV1("门店");
//								basicUnitCodeParam.setXlbStoreGroupId(store_group_id);
//								basicUnitCodeParam.setDeptId(user.getDeptId());
//								basicUnitCodeParam.setOperateId(user.getOperateId());
//								HxBasicUnitCodeResult codeResult = hxBasicUnitCodeService.findBySpec(basicUnitCodeParam);
//								if(codeResult != null) {
//									bpgp3.setDictId(Long.parseLong(codeResult.getId()+""));
//								}
//							}
//						}

                    basicPutgoodsService.save(bpgp3);
                    opp.setGetUnitId(Long.parseLong(bpgp3.getId().toString()));//卸货单位id
                    dealWithParam.setNewCustomersflag(true);
                    dealWithParam.setNewCustomers(dealWithParam.getNewCustomers() + "新收货单位：" + opp.getGetUnit() + "；");

                    BasicAddress bap3 = new BasicAddress();
                    bap3.setPutgoodsName(opp.getGetUnit());
                    bap3.setPutgoodsId(Long.parseLong(bpgp3.getId().toString()));
                    bap3.setAddress(opp.getGetUnit());
//						String address = jsonObject2.get("address").toString();
//						if (ToolUtil.isNotEmpty(address)&&!address.equals("null")) {//地址
//							bap3.setAddress(address.get());
//						}
//
////						String tel = jsonObject2.get("phone").toString();
//						if (ToolUtil.isNotEmpty(tel)&&!tel.equals("null")) {//电话
//							bap3.setTel(tel.get());
//						}

//						String contact = jsonObject2.get("contact").toString();
//						if (ToolUtil.isNotEmpty(contact)&&!contact.equals("null")) {//联系人
//							bap3.setContacts(contact);
//						}

//						String province = jsonObject2.get("province").toString();
//						if (ToolUtil.isNotEmpty(province)&&!province.equals("null")) {//省
//							bap3.setSheng(province);
//						}
//
//						String city = jsonObject2.get("city").toString();
//						if (ToolUtil.isNotEmpty(city)&&!city.equals("null")) {//市
//							bap3.setShi(city);
//						}
//
//						String district = jsonObject2.get("district").toString();
//						if (ToolUtil.isNotEmpty(district)&&!district.equals("null")) {//区
//							bap3.setQu(district);
//						}
//
//						String street = jsonObject2.get("street").toString();
//						if (ToolUtil.isNotEmpty(street)&&!street.equals("null")) {//街道
//							bap3.setJie(street);
//						}
                    bap3.setLongitude("0");
                    bap3.setLatitude("0");
                    bap3.setSwitchWl("1");
                    bap3.setSwitchBj("1500");//提货围栏半径 默认100米
                    bap3.setSwitchBj2("2000");//收货围栏半径 默认100米
                    basicAddressService.save(bap3);
                    opp.setGetLocationId(Long.parseLong(bap3.getId().toString()));//卸货地址id
                    opp.setGetLocation(bap3.getAddress());//卸货地址
                    opp.setGetPeople(bap3.getContacts());//联系人
                    opp.setGetTel(bap3.getTel());//联系电话
                }
            }
            if (!mendian) {
                basicPutgoodsService.save(bpgp3);
                opp.setGetUnitId(Long.parseLong(bpgp3.getId().toString()));//卸货单位id
                dealWithParam.setNewCustomersflag(true);
                dealWithParam.setNewCustomers(dealWithParam.getNewCustomers() + "新收货单位：" + opp.getGetUnit() + "；");

                BasicAddress bap3 = new BasicAddress();
                bap3.setPutgoodsName(opp.getGetUnit());
                bap3.setPutgoodsId(Long.parseLong(bpgp3.getId().toString()));
                bap3.setAddress(opp.getGetUnit());
                bap3.setLongitude("0");
                bap3.setLatitude("0");
                bap3.setSwitchWl("1");
                bap3.setSwitchBj("1500");//提货围栏半径 默认100米
                bap3.setSwitchBj2("2000");//收货围栏半径 默认100米
                basicAddressService.save(bap3);
                opp.setGetLocationId(Long.parseLong(bap3.getId().toString()));//卸货地址id
                opp.setGetLocation(bap3.getAddress());//卸货地址
            }
        } else {
            if (ToolUtil.isEmpty(bputr2.getXlbClientId())) {
                if (ToolUtil.isNotEmpty(client_id)) {
                    BasicPutgoods bd = new BasicPutgoods();
                    bd.setId(bputr2.getId());
                    bd.setXlbClientId(client_id);
                    basicPutgoodsService.updateById(bd);
                }
            }

            opp.setGetUnit(bputr2.getPutgoodsName());//卸货单位
            opp.setGetUnitId(Long.parseLong(bputr2.getId().toString()));//卸货单位id
            //查询卸货地点 是否存在
            BasicAddress bap3 = new BasicAddress();
            bap3.setPutgoodsId(Long.parseLong(bputr2.getId().toString()));//单位id
            BasicAddress bar2 = basicAddressService.lambdaQuery()
                    .eq(BasicAddress::getPutgoodsId, bputr2.getId())
                    .last("LIMIT 1")
                    .one();
            if (bar2 != null) {
                opp.setGetLocationId(Long.parseLong(bar2.getId().toString()));//卸货地址id
                opp.setGetLocation(bar2.getAddress());//卸货地址
                opp.setGetPeople(bar2.getContacts());//联系人
                opp.setGetTel(bar2.getTel());//联系电话
            } else {//如果没有地址
                bap3.setAddress(bputr2.getPutgoodsName());//地点 为单位名称
                bap3.setPutgoodsName(bputr2.getPutgoodsName());//单位名称
                bap3.setLongitude("0");
                bap3.setLatitude("0");
                bap3.setSwitchWl("1");
                bap3.setSwitchBj("1500");//提货围栏半径 默认100米
                bap3.setSwitchBj2("2000");//收货围栏半径 默认100米
                basicAddressService.save(bap3);
                opp.setGetLocation(bap3.getAddress());//卸货地址
                opp.setGetLocationId(Long.parseLong(bap3.getId().toString()));//卸货地址id
            }
        }
    }

    /**
     * 导出订单及明细
     *
     * @param hxOrderOutParam
     * @param condition
     * @param startTime
     * @param endTime
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/exportToExcel")
    public void exportToExcel(HttpServletResponse response, HxOrderOutParam hxOrderOutParam, String condition, String startTime, String endTime) throws IOException {
        User user = userService.getcurrentUser();
        hxOrderOutParam.setDeptId(user.getDeptId());
        if (ToolUtil.isEmpty(hxOrderOutParam.getTimeType())) {
            hxOrderOutParam.setTimeType("cj");
        }
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            hxOrderOutParam.setTimeInterval("'" + startTime + "' and '" + endTime + "'");
        } else if (startTime == null && endTime == null) {
            hxOrderOutParam.setTimeInterval("'" + DateUtil.getDate() + "' and '" + DateUtil.getDate() + "'");
        }

        List<HxOrderOutResult> hxOrderOutResults = this.hxOrderOutService.expExcel(hxOrderOutParam,condition, user.getOperateId());

        XSSFWorkbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet("出库订单及明细");


        // 创建标题行
        Row titleRow = sheet.createRow(0);
        titleRow.createCell(1).setCellValue("出库订单号");
        titleRow.createCell(2).setCellValue("收货客户");
        titleRow.createCell(3).setCellValue("收货客户备注");
        titleRow.createCell(4).setCellValue("订单状态");
        titleRow.createCell(5).setCellValue("配送日");
        titleRow.createCell(6).setCellValue("订单类型");
        titleRow.createCell(7).setCellValue("订单备注");
        titleRow.createCell(8).setCellValue("商品名称");
        titleRow.createCell(9).setCellValue("商品编码");
        titleRow.createCell(10).setCellValue("商品条码");
        titleRow.createCell(11).setCellValue("配送数量");
        titleRow.createCell(12).setCellValue("配送单位");
        titleRow.createCell(13).setCellValue("商品单价");
        titleRow.createCell(14).setCellValue("订单总价");
        titleRow.createCell(15).setCellValue("商品重量");
        titleRow.createCell(16).setCellValue("订单总量");
        titleRow.createCell(17).setCellValue("商品体积");
        titleRow.createCell(18).setCellValue("订单体积");
        titleRow.createCell(19).setCellValue("明细备注");

        // 添加数据行
        int cnt = 1;
        for (HxOrderOutResult obj : hxOrderOutResults) {
            Row row = sheet.createRow(cnt);
            row.createCell(1).setCellValue(obj.getOrderOutNumber() == null ? "" : obj.getOrderOutNumber());
            row.createCell(2).setCellValue(obj.getGetUnit() == null ? "" : obj.getGetUnit());
            row.createCell(3).setCellValue(obj.getGetUnitRemark() == null ? "" : obj.getGetUnitRemark());
            row.createCell(4).setCellValue(obj.getOrderState() == null ? "" : obj.getOrderState());
            row.createCell(5).setCellValue(obj.getPeisongTime() == null ? "" : obj.getPeisongTime());
            row.createCell(6).setCellValue(obj.getOrderType() == null ? "" : obj.getOrderType());
            row.createCell(7).setCellValue(obj.getNotes() == null ? "" : obj.getNotes());
            row.createCell(8).setCellValue(obj.getGoodsName() == null ? "" : obj.getGoodsName());
            row.createCell(9).setCellValue(obj.getGoodsNumber() == null ? "" : obj.getGoodsNumber());
            row.createCell(10).setCellValue(obj.getGoodsPcode69() == null ? "" : obj.getGoodsPcode69());
            row.createCell(11).setCellValue(obj.getPsNum() == null ? "" : obj.getPsNum());
            row.createCell(12).setCellValue(obj.getUnit() == null ? "" : obj.getUnit());
            row.createCell(13).setCellValue(obj.getGoodsPrice() == null ? "" : obj.getGoodsPrice());
            row.createCell(14).setCellValue(obj.getOutMoney() == null ? "" : obj.getOutMoney());
            row.createCell(15).setCellValue(obj.getGoodsWeight() == null ? "" : obj.getGoodsWeight());
            row.createCell(16).setCellValue(obj.getOutWeight() == null ? "" : obj.getOutWeight());
            row.createCell(17).setCellValue(obj.getGoodsVolume() == null ? "" : obj.getGoodsVolume());
            row.createCell(18).setCellValue(obj.getOutVolume() == null ? "" : obj.getOutVolume());
            row.createCell(19).setCellValue(obj.getMxNotes() == null ? "" : obj.getMxNotes());
            cnt++;
        }

        // 设置响应头
        OutputStream output = response.getOutputStream();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(("出库订单及明细" + ".xlsx").getBytes(), "iso-8859-1"));
        // 写入响应
        try (OutputStream excelOutput = output) {
            wb.write(excelOutput);
        }
        wb.close();
    }
}


